package org.restorator.controller;

import com.google.gson.Gson;
import org.restorator.entity.Item;
import org.restorator.entity.Order;
import org.restorator.service.ItemService;
import org.restorator.service.impl.ItemServiceImpl;
import org.restorator.utill.ControllerUtil;
import org.restorator.utill.GeneralUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * Controller for work with REST style requests on entity {@link Item} by it's id.
 * @author Snisar Bogdan.
 */
@WebServlet(name = "itemController", urlPatterns = "/item/*")
public class ItemController extends HttpServlet {
    private static Logger logger = LoggerFactory.getLogger(GeneralUtil.getClassName());
    private ItemService itemService = new ItemServiceImpl();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try {
            String urlStringEnd = ControllerUtil.getUrlIdMatch(req, resp);
            Integer orderId = Integer.parseInt(urlStringEnd);
            logger.trace("Get request. Try fained  item by id: {}", orderId);

            Item item = itemService.get(orderId);
            if(item != null) {
                ControllerUtil.printOk(resp, item);
            } else {
                ControllerUtil.printError(resp.getWriter());
            }
        } catch (Exception e) {
            logger.error("Exception in request processing: {}. \nStack trace: {}", e.getMessage(), e.getStackTrace());
            resp.sendError(HttpServletResponse.SC_BAD_GATEWAY);
        }
    }

}
